﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using YiSha.Data;
using YiSha.Data.Repository;
using YiSha.Entity.Business;
using YiSha.Entity.OrganizationManage;
using YiSha.Model.Param.Business;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;

namespace YiSha.Service.OrganizationManage
{
    public class PrescriptionService : RepositoryFactory
    {
        private DepartmentService departmentService = new DepartmentService();

        private PersonService personService = new PersonService();

        private TreatmentService treatmentService = new TreatmentService();

        #region 获取数据
        public async Task<List<PrescriptionEntity>> GetList(PrescriptionListParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }

        public async Task<List<PrescriptionEntity>> GetPageList(PrescriptionListParam param, Pagination pagination)
        {
            //var expression = ListFilter(param);
            //var list = await this.BaseRepository().FindList(expression, pagination);

            StringBuilder strSql = new StringBuilder();
            var parameter = new List<DbParameter>();

            strSql.Append(@"select a.IsEnd,d.Title as TreatmentName,d.Content as TreatmentContent ,a.id,a.BaseCreateTime,a.BaseModifyTime,a.PersonId,b.RealName,Gender,Birthday,Mobile,WorkUnit,Address,DepartmentId,c.DepartmentName,
                        case when  (select max(FollowUpSort) from BsEyeFollowUp where a.Id=BsEyeFollowUp.PrescriptionId) is null then 0 else 
                        (select max(FollowUpSort) from BsEyeFollowUp where a.Id=BsEyeFollowUp.PrescriptionId) end as FollowUpSort 
                        from BsPrescription a 
                        left join BsPerson b on a.PersonId = b.Id
                        left join SysDepartment c on b.DepartmentId = c.Id 
                        left join SysTreatment d on a.TreatmentId=d.id where a.BaseIsDelete=0 ");

            if (param != null)
            {
                if (!string.IsNullOrEmpty(param.Key))
                {
                    strSql.Append(" and (b.RealName like @key or b.RealNameEn like @key or b.Mobile like @key )");

                    parameter.Add(DbParameterExtension.CreateDbParameter("@key", "%" + param.Key + "%"));
                }

                if (!string.IsNullOrEmpty(param.DepartmentId))
                {
                    var dps = Convert.ToInt64(param.DepartmentId.Split(",").Last());
                    var departmentEntity = departmentService.GetList(dps);
                    var dpsNew = string.Join(",", departmentEntity.Result.Select(e => e.Id).ToArray());

                    if (!string.IsNullOrEmpty(dpsNew))
                    {
                        strSql.Append(" and ( b.DepartmentId in ( " + dpsNew + " ) or b.DepartmentId=" + dps + " )");
                    }
                    else
                    {
                        strSql.Append(" and  b.DepartmentId=" + dps + " ");
                    }
                }

                if (param.StartTime.HasValue || param.EndTime.HasValue)
                {
                    strSql.Append("and a.id in (select PrescriptionId from BsEyeFollowUp where BaseIsDelete=0 ");
                    if (param.StartTime.HasValue)
                    {
                        strSql.Append(" and NextFollowUpTime >=@StartTime");
                        parameter.Add(DbParameterExtension.CreateDbParameter("@StartTime", param.StartTime.Value));
                    }
                    if (param.EndTime.HasValue)
                    {
                        strSql.Append(" and NextFollowUpTime<=@EndTime");
                        parameter.Add(DbParameterExtension.CreateDbParameter("@EndTime", param.EndTime.Value));
                    }

                    strSql.Append(" )");
                }




            }

            var list = await this.BaseRepository().FindList<PrescriptionEntity>(strSql.ToString(), parameter.ToArray(), pagination);

            return list.ToList();
        }

        public async Task<PrescriptionEntity> GetEntity(long id)
        {

            var model = this.BaseRepository().FindEntity<PrescriptionEntity>(id).Result;

            var personModel = personService.GetEntity(model.PersonId.Value).Result;
            var treatmentModel = treatmentService.GetEntity(model.TreatmentId).Result;

            model.RealName = personModel.RealName;
            model.Gender = personModel.Gender;
            model.Birthday = personModel.Birthday;
            model.OccupationValue = personModel.OccupationValue;
            model.Mobile = personModel.Mobile;
            model.WorkUnit = personModel.WorkUnit;
            model.DepartmentId = personModel.DepartmentId;
            model.TreatmentContent = treatmentModel.Content;

            if (model.DepartmentId > 0)
            {
                DepartmentEntity departmentEntity = await departmentService.GetEntity(model.DepartmentId);
                if (departmentEntity != null)
                {
                    model.DepartmentName = departmentEntity.DepartmentName;
                }
            }

            //后期改造使用原生sql

            return model;
        }



        public bool ExistPersonName(PrescriptionEntity entity)
        {
            var expression = LinqExtensions.True<PrescriptionEntity>();
            expression = expression.And(t => t.BaseIsDelete == 0);
            if (entity.Id.IsNullOrZero())
            {
                expression = expression.And(t => t.PersonId == entity.PersonId && t.IsEnd == 0 && t.BaseIsDelete == 0);
            }
            else
            {
                expression = expression.And(t => t.PersonId == entity.PersonId && t.BaseIsDelete == 0 && t.IsEnd == 0 && t.Id != entity.Id);
            }
            return this.BaseRepository().IQueryable(expression).Count() > 0 ? true : false;
        }
        #endregion

        #region 提交数据
        public async Task SaveForm(PrescriptionEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                await entity.Create();
                await this.BaseRepository().Insert<PrescriptionEntity>(entity);
            }
            else
            {
                await entity.Modify();
                await this.BaseRepository().Update(entity);
            }
        }

        public async Task DeleteForm(string ids)
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');
            await this.BaseRepository().Delete<PrescriptionEntity>(idArr);
        }
        #endregion

        #region 私有方法
        private Expression<Func<PrescriptionEntity, bool>> ListFilter(PrescriptionListParam param)
        {
            var expression = LinqExtensions.True<PrescriptionEntity>();
            if (param != null)
            {
                if (!string.IsNullOrEmpty(param.Key))
                {
                    // expression = expression.And(t => t.RealName.Contains(param.Key) || t.ContactsName.Contains(param.Key) || t.Mobile.Contains(param.Key) || t.RealNameEn.Contains(param.Key));
                }




                if (!string.IsNullOrEmpty(param.DepartmentId))
                {
                    var dps = Convert.ToInt64(param.DepartmentId.Split(",").Last());
                    var departmentEntity = departmentService.GetList(dps);


                    //expression = expression.And(t => departmentEntity.Result.Select(e => e.Id).ToList().Contains(t.DepartmentId) || t.DepartmentId == dps);
                }

            }



            return expression;
        }
        #endregion
    }
}
